
// <copyright file="TelnetHelper.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   The telnet helper.
// </summary>

namespace SubhadraSolutions.Sharp.Utils.Net
{
    using System;
    using System.Threading;

    /// <summary>
    /// The telnet helper.
    /// </summary>
    public sealed class TelnetHelper : AbstractDisposable
    {
        #region Fields

        /// <summary>
        /// The new result wait handle.
        /// </summary>
        private readonly AutoResetEvent _newResultWaitHandle = new AutoResetEvent(false);

        /// <summary>
        /// The t wrapper.
        /// </summary>
        private readonly TelnetWrapper tWrapper;

        /// <summary>
        /// The expected string.
        /// </summary>
        private volatile string _expectedString;

        /// <summary>
        /// The result.
        /// </summary>
        private volatile string _result;

        #endregion Fields

        #region Constructors and Finalizers

        /// <summary>
        /// Initializes a new instance of the <see cref="TelnetHelper"/> class.
        /// </summary>
        /// <param name="wrapper">
        /// The wrapper.
        /// </param>
        /// <param name="commandPrompt">
        /// The command prompt.
        /// </param>
        internal TelnetHelper(TelnetWrapper wrapper, string commandPrompt)
        {
            this.tWrapper = wrapper;
            this.tWrapper.DataAvailable += this.tWrapper_DataAvailable;
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="TelnetHelper"/> class.
        /// </summary>
        ~TelnetHelper()
        {
            this.Dispose(false);
        }

        #endregion Constructors and Finalizers

        #region Public Methods and Operators

        /// <summary>
        /// The create telnet session.
        /// </summary>
        /// <param name="hostName">
        /// The host name.
        /// </param>
        /// <param name="port">
        /// The port.
        /// </param>
        /// <param name="commandPrompt">
        /// The command prompt.
        /// </param>
        /// <param name="loginPrompt">
        /// The login prompt.
        /// </param>
        /// <param name="login">
        /// The login.
        /// </param>
        /// <param name="passwordPrompt">
        /// The password prompt.
        /// </param>
        /// <param name="password">
        /// The password.
        /// </param>
        /// <param name="errorHandler">
        /// The error handler.
        /// </param>
        /// <param name="disconnectedEventHandler">
        /// The disconnected event handler.
        /// </param>
        /// <returns>
        /// The <see cref="TelnetHelper"/>.
        /// </returns>
        public static TelnetHelper CreateTelnetSession(string hostName, int port, string commandPrompt, string loginPrompt, string login, string passwordPrompt, string password, EventHandler<OnExceptionEventArgs> errorHandler, EventHandler disconnectedEventHandler)
        {
            var tWrapper = new TelnetWrapper();
            tWrapper.OnException += errorHandler;
            tWrapper.Disconnected += disconnectedEventHandler;
            tWrapper.HostName = hostName;
            tWrapper.Port = port;
            var helper = new TelnetHelper(tWrapper, commandPrompt);
            tWrapper.Connect();
            helper.WaitFor(loginPrompt);
            helper.SendCommand(login, passwordPrompt, 0);
            helper.SendCommand(password, commandPrompt, 0);
            return helper;
        }

        /// <summary>
        /// The disconnect.
        /// </summary>
        public void Disconnect()
        {
            if (this.tWrapper.Connected)
            {
                this.tWrapper.Disconnect();
            }
        }

        /// <summary>
        /// The send command.
        /// </summary>
        /// <param name="command">
        /// The command.
        /// </param>
        /// <param name="expectedString">
        /// The expected string.
        /// </param>
        /// <param name="timeoutInMilliSeconds">
        /// The timeout in milli seconds.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string SendCommand(string command, string expectedString, int timeoutInMilliSeconds)
        {
            this._result = null;
            this._newResultWaitHandle.Reset();
            this._expectedString = expectedString;
            this.tWrapper.Send(command + this.tWrapper.CRLF);
            this.tWrapper.Receive();
            if (!string.IsNullOrEmpty(expectedString))
            {
                this._newResultWaitHandle.WaitOne(timeoutInMilliSeconds);
            }

            string s = this._result;
            this._result = null;
            this._expectedString = null;
            return s;
        }

        /// <summary>
        /// The wait for.
        /// </summary>
        /// <param name="expectedString">
        /// The expected string.
        /// </param>
        public void WaitFor(string expectedString)
        {
            this._result = null;
            this._newResultWaitHandle.Reset();
            this._expectedString = expectedString;
            this.tWrapper.Receive();
            if (!string.IsNullOrEmpty(expectedString))
            {
                this._newResultWaitHandle.WaitOne();
            }

            this._result = null;
            this._expectedString = null;
        }

        #endregion Public Methods and Operators

        #region Methods

        /// <summary>
        /// The dispose.
        /// </summary>
        /// <param name="disposing">
        /// The disposing.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            this.Disconnect();
            this._newResultWaitHandle.Dispose();
        }

        /// <summary>
        /// The t wrapper_ data available.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void tWrapper_DataAvailable(object sender, DataAvailableEventArgs e)
        {
            this._result += e.Data;
            if (!string.IsNullOrEmpty(this._expectedString))
            {
                if (e.Data.Contains(this._expectedString) || (this._result != null && this._result.Contains(this._expectedString)))
                {
                    this._newResultWaitHandle.Set();
                }
            }
        }

        /// <summary>
        /// The t wrapper_ on exception.
        /// </summary>
        /// <param name="e">
        /// The e.
        /// </param>
        private void tWrapper_OnException(Exception e)
        {
        }

        #endregion Methods
    }
}
